package com.mtons.mblog.modules.repository;

import com.mtons.mblog.modules.entity.Answer;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface AnswerRepository extends JpaRepository<Answer, Long>, JpaSpecificationExecutor<Answer> {
    Page<Answer> findAllByAuthorId(Pageable pageable, long userId);

    @Query("select coalesce(max(weight), 0) from Answer")
    int maxWeight();

    @Modifying
    @Query("update Answer set views = views + :increment where id = :id")
    void updateViews(@Param("id") long id, @Param("increment") int increment);

    @Modifying
    @Query("update Answer set comments = comments + :increment where id = :id")
    void updateComments(@Param("id")long id, @Param("increment") int increment);

    @Modifying
    @Query("update Answer set comments = comments + :increment where id = :id")
    void updateFavors(@Param("id") long answerId, @Param("increment") int increment);

    List<Answer> findByQuestId(long questId);
}
